using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using SmartHealthcare.Write.Api.Application.Command.Medicine;
using System.Threading;
using System.Threading.Tasks;

namespace SmartHealthcare.Write.Api.Application.Handler.Medicine
{
    /// <summary>
    /// 药品修改处理器
    /// </summary>
    public class UpdateMedicineHandler : IRequestHandler<UpdateMedicineCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<MedicineModel> _medicineRepository;

        public UpdateMedicineHandler(IBaseRepository<MedicineModel> medicineRepository)
        {
            _medicineRepository = medicineRepository;
        }

        public async Task<APIResult<bool>> Handle(UpdateMedicineCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据药品ID查找药品
                var medicine = _medicineRepository.GetModel(request.Id);
                if (medicine == null)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "药品不存在",
                        Data = false
                    };
                }

                // 更新药品信息
                medicine.Specification = request.Specification;
                medicine.DosageForm = request.DosageForm;
                medicine.DrugType = request.DrugType;
                medicine.CostName = request.CostName;
                medicine.Inventory = request.Inventory;
                medicine.InventoryLimit = request.InventoryLimit;
                medicine.InventoryLowerLimit = request.InventoryLowerLimit;
                medicine.Price = request.Price;
                medicine.PurchasePrice = request.PurchasePrice;
                medicine.Date_ofManufacture = request.Date_ofManufacture ?? DateTime.Now;
                medicine.EffectiveDate = request.EffectiveDate ?? DateTime.Now;
                medicine.Effect = request.Effect;

                // 保存更改
                var result = _medicineRepository.Update(medicine);
                return new APIResult<bool>
                {
                    Code = result > 0 ? APIEnums.Success : APIEnums.Fail,
                    Msg = result > 0 ? "药品修改成功" : "药品修改失败",
                    Data = result > 0
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnums.Error,
                    Msg = $"药品修改失败：{ex.Message}",
                    Data = false
                };
            }
        }
    }
}
